package com.ruoyi.controller;

import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponseBody;
import com.aliyun.tea.TeaException;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.config.HttpUtils;
import com.ruoyi.config.MD5Utils;
import com.ruoyi.config.OSSFileUtil;
import com.ruoyi.domain.DriverCertificate;
import com.ruoyi.service.IDriverCertificateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ntl")
public class NtlController {


    /**
     * 测试
     */
    @RequestMapping("/test")
    public String test() {
        return "Hello, World!";
    }

    /**
     * 使用AK&SK初始化账号Client
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.ocr_api20210707.Client createClient(String accessKeyId,String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }

    @PostMapping("/ocr")
    public Object ocr(MultipartFile file) throws Exception {
        com.aliyun.ocr_api20210707.Client client = NtlController.createClient("LTAI5t65CrHFuZh7e26S1koe", "YRVrv1Px3VtQorrOcw4a9nSxZM201R");
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        java.io.InputStream bodyStream = file.getInputStream();
        com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest recognizeIdcardRequest = new com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest()
                .setBody(bodyStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeIdcardResponse idcard = client.recognizeIdcardWithOptions(recognizeIdcardRequest, runtime);
            RecognizeIdcardResponseBody body = idcard.getBody();
            String data = body.getData();
            return data;
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }

    private static final String appId = "bC9tpHEqKDQwruM8";
    private static final String appSecurity = "bC9tpHEqKDQwruM8KQpg8KAMFt3VFY0O";


    @PostMapping("/addFile")
    public AjaxResult addFile(MultipartFile file) throws IOException {
        OSSFileUtil ossFileUtil1 = new OSSFileUtil();
        String s = ossFileUtil1.uploadFile(file);
        System.out.println(s);
        return AjaxResult.success(s);
    }

    @PostMapping("/faceLive")
    public AjaxResult faceLive(){
        String timestamp = System.currentTimeMillis() + "";
        //接口地址
        String urls = "https://api.shumaidata.com/v4/liveness/h5/token";
        String returnUrl = "http://localhost:9090/#/driver/work/idcard";
        //MD5Utils文件请联系工作人员索取
        String sign = MD5Utils.encrypt(appId+"&"+timestamp+"&"+appSecurity);
        System.out.println("--------timestamp: "+timestamp);
        System.out.println("--------sign: "+sign);

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("appid",appId);
        params.put("timestamp",timestamp);
        params.put("sign",sign);
        params.put("returnUrl",returnUrl);

        //HttpUtils文件请联系工作人员索取
        String result = HttpUtils.get(urls,null,params);
        System.out.println(result);
        return AjaxResult.success(result);
    }

    @PostMapping("/testFace/{token}")
    public AjaxResult testFace(@PathVariable String token){
        String timestamp = System.currentTimeMillis() + "";
        String urls = "https://api.shumaidata.com/v4/liveness/h5/result";
        String sign = MD5Utils.encrypt(appId+"&"+timestamp+"&"+appSecurity);
        System.out.println("最后的-------------sign: "+sign);
        System.out.println("最后的-------------timestamp: "+timestamp);
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("appid",appId);
        params.put("timestamp",timestamp);
        params.put("sign",sign);
        params.put("token",token);
        String result = HttpUtils.get(urls,null,params);
        System.out.println("最后的-------------"+result);
        return AjaxResult.success(result);
    }

    @Autowired
    IDriverCertificateService iDriverCertificateService;


    @PostMapping("/testFun")
    public AjaxResult testFun(@RequestBody DriverCertificate driverCertificate){

        //获取前端userid
        Long userId = SecurityUtils.getUserId();
        DriverCertificate driverCertificate1 = iDriverCertificateService.selectDriverCertificateById(userId);
        if (driverCertificate1 != null){
            return AjaxResult.error("您已经提交过信息了");
        }
        if (driverCertificate==null){
            return AjaxResult.error("请先提交信息");
        }
        DriverCertificate xindedr = new DriverCertificate();
        xindedr.setDriverId(userId);
        xindedr.setDriverRelname(driverCertificate.getDriverRelname());
        xindedr.setDriverSex(driverCertificate.getDriverSex());
        xindedr.setDriverAddress(driverCertificate.getDriverAddress());
        xindedr.setDriverIdcard(driverCertificate.getDriverIdcard());
        iDriverCertificateService.insertDriverCertificate(xindedr);
        return AjaxResult.success();
    }


    @PostMapping("/testFun1")
    public AjaxResult testFun1(@RequestBody DriverCertificate driverCertificate){

        Long userId = SecurityUtils.getUserId();
//        DriverCertificate driverCertificate1 = iDriverCertificateService.selectDriverCertificateById(userId);
//        Long id = driverCertificate1.getId();
//        if (driverCertificate1 != null){
//            return AjaxResult.error("您已经提交过信息了");
//        }
//        if (driverCertificate==null){
//            return AjaxResult.error("请先提交信息");
//        }
        driverCertificate.setDriverId(userId);
        driverCertificate.setDriverTime(new Date());
        iDriverCertificateService.updateDriverCertificate(driverCertificate);
        return AjaxResult.success();
    }

}
